package com.its.us.web.service.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.its.us.web.entity.sys.Menu;
import com.its.us.web.mapper.sys.MenuMapper;
import com.its.us.web.utils.Tree.TreeMenu;
import com.its.us.web.utils.Tree.TreeUtil;
import com.its.us.web.vo.sys.ResultBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huguangjun
 * @className MenuService
 * @date 2020/12/3
 * @desc 9:07
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class MenuService {

    @Resource
    private MenuMapper menuMapper;

    /**
     * get current menu for username
     *
     * @param username
     * @return
     * @throws Exception
     */
    public List<Menu> getCurrentMenus(String username) throws Exception {
        return menuMapper.getCurrentMenus(username);
    }

    /**
     * for current menus as util class
     *
     * @param username
     * @return
     * @throws Exception
     */
    public List<TreeMenu> getCurrentMenu(String username) throws Exception {
        List<Menu> menus = menuMapper.getCurrentMenus(username);
        List<TreeMenu> tree = TreeUtil.getCurrentMenus(menus);
        return tree;
    }

    /**
     * for all menus as util class
     *
     * @return
     * @throws Exception
     */
    public List<TreeMenu> getAllMenus() throws Exception {
        List<Menu> menus = menuMapper.getAllMenus();
        List<TreeMenu> tree = TreeUtil.getAllMenus(menus);
        return tree;
    }

    /**
     * save menu
     *
     * @param menu
     * @return
     * @throws Exception
     */
    public ResultBean saveMenu(Menu menu) throws Exception {
        if (StringUtils.isNotEmpty(menu.getId())) {
            // add sub menu
            // get menu by id
            QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", menu.getId());
            Menu obj = menuMapper.selectOne(queryWrapper);
            if (null != obj) {
                Menu entity = new Menu();
                entity.setParentId(menu.getId());
                if(menu.getIsButton().equals("0")){
                    entity.setIcons("icon-button");
                }else{
                    entity.setIcons(menu.getIcons());
                }
                entity.setIsButton(menu.getIsButton());
                entity.setMenuDes(menu.getMenuDes());
                entity.setMenuName(menu.getMenuName());
                entity.setMenuUrl(menu.getMenuUrl());
                entity.setPermission(menu.getPermission());
                entity.setSort(menu.getSort());
                // insert
                menuMapper.insert(entity);
                // update
                QueryWrapper<Menu> updateWrapper = new QueryWrapper<>();
                updateWrapper.eq("id", entity.getId());
                entity.setMenuId(entity.getId());
                entity.setMenuLevel(obj.getMenuLevel() + "," + entity.getId());
                menuMapper.update(entity, updateWrapper);
            } else {
                return new ResultBean("数据异常.");
            }
        } else {
            // add root menu
            Menu entity = new Menu();
            entity.setParentId("0");
            entity.setIcons(menu.getIcons());
            entity.setIsButton(menu.getIsButton());
            entity.setMenuDes(menu.getMenuDes());
            entity.setMenuName(menu.getMenuName());
            entity.setMenuUrl(menu.getMenuUrl());
            entity.setPermission(menu.getPermission());
            entity.setSort(menu.getSort());
            // insert
            menuMapper.insert(entity);
            // update
            QueryWrapper<Menu> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("id", entity.getId());
            entity.setMenuId(entity.getId());
            entity.setMenuLevel("0," + entity.getId());
            menuMapper.update(entity, updateWrapper);
        }
        return new ResultBean("操作成功.");
    }


    /**
     * 修改菜单
     * @param menu
     * @return
     */
    public ResultBean updateMenu(Menu menu) {
        if (StringUtils.isNotEmpty(menu.getId())) {
            QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", menu.getId());
            Menu obj = menuMapper.selectOne(queryWrapper);
            if (null != obj) {
                // update param
                QueryWrapper<Menu> updateWrapper = new QueryWrapper<>();
                updateWrapper.eq("id", menu.getId());
                Menu entity = updateMenuSetVal(menu, obj);
                menuMapper.update(entity, updateWrapper);
            } else {
                return new ResultBean("数据异常.");
            }
        }
        return new ResultBean("操作成功.");
    }

    /**
     * private update menu set val
     * @param menu
     * @param obj
     * @return
     */
    private Menu updateMenuSetVal(Menu menu, Menu obj) {
        Menu entity = new Menu();
        // first icons
        if(StringUtils.isNotEmpty(obj.getIcons())){
            if(!obj.getIcons().equals(menu.getIcons())){
                entity.setIcons(menu.getIcons());
            }
        }

        // second for button is icons
        // todo: 系统默认按钮图标
        if(StringUtils.isNotEmpty(obj.getIsButton())){
            if(!obj.getIsButton().equals(menu.getIsButton())){
                entity.setIsButton(menu.getIsButton());
                if(menu.getIsButton().equals("0")){
                    entity.setIcons("icon-button");
                }else{
                    entity.setIcons(menu.getIcons());
                }
            }
        }else{
            if(StringUtils.isNotEmpty(menu.getIsButton())){
                if(menu.getIsButton().equals("0")){
                    entity.setIcons("icon-button");
                }else{
                    entity.setIcons(menu.getIcons());
                }
            }
        }

        if(StringUtils.isNotEmpty(obj.getMenuDes())){
            if(!obj.getMenuDes().equals(menu.getMenuDes())){
                entity.setMenuDes(menu.getMenuDes());
            }
        }else{
            if(StringUtils.isNotEmpty(menu.getMenuDes())){
                entity.setMenuDes(menu.getMenuDes());
            }
        }
        if(StringUtils.isNotEmpty(obj.getMenuName())){
            if(!obj.getMenuName().equals(menu.getMenuName())){
                entity.setMenuName(menu.getMenuName());
            }
        }else{
            if(StringUtils.isNotEmpty(menu.getMenuName())){
                entity.setMenuName(menu.getMenuName());
            }
        }
        if(StringUtils.isNotEmpty(obj.getMenuUrl())){
            if(!obj.getMenuUrl().equals(menu.getMenuUrl())){
                entity.setMenuUrl(menu.getMenuUrl());
            }
        }else{
            if(StringUtils.isNotEmpty(menu.getMenuUrl())){
                entity.setMenuUrl(menu.getMenuUrl());
            }
        }
        if(StringUtils.isNotEmpty(obj.getPermission())){
            if(!obj.getPermission().equals(menu.getPermission())){
                entity.setPermission(menu.getPermission());
            }
        }else{
            if(StringUtils.isNotEmpty(menu.getPermission())){
                entity.setPermission(menu.getPermission());
            }
        }
        entity.setSort(menu.getSort());
        return entity;
    }

    /**
     * 菜单删除
     *
     * @param ids
     * @return
     */
    public ResultBean deleteByIds(List<String> ids) throws Exception {
        if (ids.size() > 0) {

            for(int i=0;i<ids.size();i++){
                List<String> dataId = new ArrayList<>();
                List<String> deleteIds = getIds(ids.get(i), dataId);
                deleteIds.add(ids.get(i));
                // del menu
                menuMapper.deleteBatchIds(deleteIds);
                // del role_menu
                menuMapper.deleteByMenuId(deleteIds);
            }
            // 遍历级联删除
            /*ids.forEach(id -> {
                List<String> dataId = new ArrayList<>();
                List<String> deleteIds = getIds(id, dataId);
                deleteIds.add(id);
                menuMapper.deleteBatchIds(deleteIds);
                //del sys_role_menu
                try {
                    menuMapper.deleteByMenuId(deleteIds);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });*/
        }
        return new ResultBean("操作成功.");
    }

    /**
     * get delete ids
     * 递归
     * @param id
     * @param ids
     * @return
     */
    private List<String> getIds(String id, List<String> ids) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Menu> menus = menuMapper.selectList(queryWrapper);
        if (menus.size() > 0) {
            menus.forEach(m -> {
                ids.add(m.getId());
                getIds(m.getId(), ids);
            });
        }
        return ids;
    }

    /**
     * 详情
     * @param id
     * @return
     */
    public Menu findById(String id) {
        return menuMapper.selectById(id);
    }

    /**
     * get role menu by roleId
     * @param roleId
     * @return
     */
    public List<Menu> getMenuByRoleId(String roleId) throws Exception {
        return menuMapper.getMenuByRoleId(roleId);
    }
}
